﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DeliveryService
{
    public class BLFoodsOrder
    {
        /// <summary>
        /// 提交新的菜品订单
        /// OrderForm
        /// OrderForm_History
        /// OrderForm_Maker 需要一默认员工 : admin
        /// OrderForm_Foods
        /// </summary>
        /// <param name="studentId">学生id</param>
        /// <param name="addressId">地址id</param>
        /// <param name="TotalAmount">商品总金额</param>
        /// <param name="privilegeAmount">优惠金额</param>
        /// <param name="payableAmount">应付金额</param>
        /// <param name="comment">备注</param>
        /// <param name="goodsIdAndAmount">商品id和对应的数量,需要按照以下格式传输,如:
        /// [{"Id":1,"Amount":2},{"Id":2,"Amount":1},{"Id":3,"Amount":3}]</param>
        /// <returns>订单ID</returns>
        public string AddNewFoodsOrder(int studentId, int addressId, double TotalAmount, double privilegeAmount,
                                    double payableAmount, string comment, string foodsIdAndAmount)
        {
            try
            {
                using (DeliveryDBDataContext db = new DeliveryDBDataContext())
                {
                    DateTime dt = DateTime.Now;
                    var order = new OrderForm
                    {
                        Address = db.Addresses.Single(a => a.Address_Id == addressId),
                        Student = db.Students.Single(s => s.Students_Id == studentId),
                        Amount = (decimal)TotalAmount,
                        Privilege_Amount = (decimal)privilegeAmount,
                        Payable_Amount = (decimal)payableAmount,
                        Comment = comment,
                        Status = (int)OrderStatus.waitingShipped,
                        OrderFormNumber = BaseClass.GenerateOrderNumber(),
                        IsReservation = false,
                        CreateTime = dt
                    };
                    db.OrderForms.InsertOnSubmit(order);
                    db.SubmitChanges();
                    var history = new OrderForm_History
                    {
                        OrderForm = order,
                        OrderForm_Maker = db.OrderForm_Makers.OrderBy(m => m.OrderForm_Staff_Id).FirstOrDefault(),
                        OrderStatus = (int)OrderStatus.waitingShipped,
                        SubmitTime = dt,
                        Comment = "新订单,待发货.",
                    };
                    db.OrderForm_Histories.InsertOnSubmit(history);
                    db.SubmitChanges();
                    var foods = JArray.Parse(foodsIdAndAmount).Select(x => new OrderForm_Food
                    {
                        Food = db.Foods.Single(f => f.Foods_Id == int.Parse(x["Id"].ToString())),
                        Amount = int.Parse(x["Amount"].ToString()),
                        OrderForm = order
                    });
                    db.OrderForm_Foods.InsertAllOnSubmit(foods);
                    db.SubmitChanges();
                    return order.OrderFormNumber;
                }
            }
            catch (Exception ex)
            {
                throw;
                // return -1;
            }
        }


        /// <summary>
        /// 根据学生姓名获取此学生的菜品订单
        /// </summary>
        /// <param name="studentId">学生ID</param>
        /// <returns>菜品订单详情</returns>
        public string GetFoodsOrderFormsByStudentId(int studentId)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                var query = db.OrderForms.Where(o => o.Student.Students_Id == studentId && o.OrderForm_Foods.Count() > 0)
                              .OrderByDescending(o => o.CreateTime)
                              .Select(o => new
                                        {
                                            OrderFormId = o.OrderForm_Id,
                                            Address = o.Address.Address_Info,
                                            Comment = o.Comment,
                                            PayableAmount = o.Payable_Amount.HasValue ? (double)o.Payable_Amount.Value : 0,
                                            PrivilegeAmount = o.Privilege_Amount.HasValue ? (double)o.Privilege_Amount.Value : 0,
                                            TotalAmount = o.Amount.HasValue ? (double)o.Amount.Value : 0,
                                            Status = o.Status,
                                            OrderFormNumber = o.OrderFormNumber,
                                            CreateTime = o.CreateTime,
                                            FoodsList = o.OrderForm_Foods.Select(g => new
                                                            {
                                                                FoodsId = g.Food.Foods_Id,
                                                                Amount = g.Amount,
                                                                FoodPicture = g.Food.Foods_Pic
                                                            })
                                        });
                return JsonConvert.SerializeObject(query);
            }
        }

        /// <summary>
        /// 根据学生ID和订单状态查询菜品订单
        /// </summary>
        /// <param name="studentId">学生ID</param>
        /// <param name="orderStatus">订单状态</param>
        /// <returns>菜品订单详情</returns>
        public string GetFoodsOrderFormsByStatues(int studentId, int orderStatus)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                var query = db.OrderForms.Where(o => o.Student.Students_Id == studentId && o.Status == orderStatus && o.OrderForm_Foods.Count() > 0)
                              .OrderByDescending(o => o.CreateTime)
                              .Select(o => new
                                        {
                                            OrderFormId = o.OrderForm_Id,
                                            Address = o.Address.Address_Info,
                                            Comment = o.Comment,
                                            PayableAmount = o.Payable_Amount.HasValue ? (double)o.Payable_Amount.Value : 0,
                                            PrivilegeAmount = o.Privilege_Amount.HasValue ? (double)o.Privilege_Amount.Value : 0,
                                            TotalAmount = o.Amount.HasValue ? (double)o.Amount.Value : 0,
                                            Status = o.Status,
                                            OrderFormNumber = o.OrderFormNumber,
                                            CreateTime = o.CreateTime,
                                            FoodsList = o.OrderForm_Foods.Select(g => new
                                            {
                                                GoodsId = g.Food.Foods_Id,
                                                Amount = g.Amount,
                                                FoodPicture = g.Food.Foods_Pic
                                            })
                                        });
                return JsonConvert.SerializeObject(query);
            }
        }

        /// <summary>
        /// 根据订单号获取该订单对应的菜品对象和商品数量
        /// </summary>
        /// <param name="orderFormNumber">订单号</param>
        /// <returns>菜品订单详情</returns>
        public string GetFoodsOrderFormsByOrderFormNumber(string orderFormNumber)
        {
            using (DeliveryDBDataContext db = new DeliveryDBDataContext())
            {
                var query = db.OrderForms.Where(o => o.OrderFormNumber == orderFormNumber && o.OrderForm_Foods.Count() > 0)
                              .OrderByDescending(o => o.CreateTime)
                              .Select(o => new
                                {
                                    OrderFormId = o.OrderForm_Id,
                                    Address = o.Address.Address_Info,
                                    Comment = o.Comment,
                                    PayableAmount = o.Payable_Amount.HasValue ? (double)o.Payable_Amount.Value : 0,
                                    PrivilegeAmount = o.Privilege_Amount.HasValue ? (double)o.Privilege_Amount.Value : 0,
                                    TotalAmount = o.Amount.HasValue ? (double)o.Amount.Value : 0,
                                    Status = o.Status,
                                    CreateTime = o.CreateTime,
                                    OrderFormNumber = o.OrderFormNumber,
                                    FoodsList = o.OrderForm_Foods.Select(g => new
                                    {
                                        GoodsId = g.Food.Foods_Id,
                                        Amount = g.Amount,
                                        FoodPicture = g.Food.Foods_Pic
                                    })
                                });
                return JsonConvert.SerializeObject(query);
            }
        }
    }
}